/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 98152
 * Date: 2024-06-03
 * Time: 16:52
 */
import java.util.concurrent.locks.*;

class ComputerFactory {
    private int computerCount = 0;
    private final Lock lock = new ReentrantLock();
    private final Condition produced = lock.newCondition();
    private final Condition consumed = lock.newCondition();

    public void produce() throws InterruptedException {
        lock.lock();
        try {
            // 如果有计算机未被搬走，则等待
            while (computerCount != 0) {
                consumed.await();
            }
            // 生产计算机
            computerCount++;
            System.out.println("生产了一台电脑，当前电脑数量：" + computerCount);
            // 通知搬运工可以搬走计算机
            produced.signal();
        } finally {
            lock.unlock();
        }
    }

    public void consume() throws InterruptedException {
        lock.lock();
        try {
            // 如果没有计算机可搬走，则等待
            while (computerCount == 0) {
                produced.await();
            }
            // 搬走计算机
            computerCount--;
            System.out.println("搬走了一台电脑，当前电脑数量：" + computerCount);
            // 通知生产线程可以生产新的计算机
            consumed.signal();
        } finally {
            lock.unlock();
        }
    }
}

class Producer implements Runnable {
    private final ComputerFactory factory;

    public Producer(ComputerFactory factory) {
        this.factory = factory;
    }

    public void run() {
        try {
            while (true) {
                factory.produce();
                Thread.sleep(1000); // 模拟生产计算机的时间
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Consumer implements Runnable {
    private final ComputerFactory factory;

    public Consumer(ComputerFactory factory) {
        this.factory = factory;
    }

    public void run() {
        try {
            while (true) {
                factory.consume();
                Thread.sleep(1500); // 模拟搬运计算机的时间
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public class Main {
    public static void main(String[] args) {
        ComputerFactory factory = new ComputerFactory();
        Thread producerThread = new Thread(new Producer(factory));
        Thread consumerThread = new Thread(new Consumer(factory));

        producerThread.start();
        consumerThread.start();
    }
}
